﻿using LY.Business.ServiceImpl;
using LY.Common;
using LY.Common.Utils;
using LY.Common.Utils.Sf_Struct;
using LY.Common.Utils.Sign;
using LY.Entity;
using LY.Entity.Entities;
using LY.Entity.Jsons;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Interface;
using QJ.CMS.Filters;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;

namespace QJ.CMS.Controllers
{
    [MyAuthorization]
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        private readonly ISiteconfigService _siteconfigService;
        private IMemberService _memberService;
        private IBankCardService _bank;
        private ISysTemplateService _templateService;
        private IAccountService _aservice;
        private ILoginService _lservice;
        private ICompanyService _companyService;

        private IFundsFlowService _fservice;
        private IBankInfoService _bankInfo;
        private ICompanydocumentService _companydocument;



        private static string _sftAddress = ConfigurationManager.AppSettings["SftAddress"];
        private static string _merchantNo = ConfigurationManager.AppSettings["merchantNo"];
        private static string _backAddress = ConfigurationManager.AppSettings["BackAddress"];
        private static string _rechargeAddress = ConfigurationManager.AppSettings["RechargeAddress"];
        private static string _apiAddress = ConfigurationManager.AppSettings["ApiAddress"];
        public AccountController(IMemberService memberService, IBankCardService bank, ISysTemplateService templateService, IAccountService aService, ILoginService lService, ICompanyService companyService, IFundsFlowService fService, ISiteconfigService siteconfigService, IBankInfoService bankInfo, ICompanydocumentService companydocument)
        {
            _memberService = memberService;
            _bank = bank;
            _templateService = templateService;
            _aservice = aService;
            _lservice = lService;
            _companyService = companyService;

            _fservice = fService;
            _siteconfigService = siteconfigService;
            _bankInfo = bankInfo;
            _companydocument = companydocument;
        }

        #region 资产总览
        public ActionResult Index()
        {
            U_Company company = null;
            if (Session["CurrentUser"] != null)
            {
                U_Member member = (U_Member)Session["CurrentUser"];
                ViewBag.SftAddress = _sftAddress;
                ViewBag.merchantNo = _merchantNo;
                ViewBag.SFTUserId = member.SFTUserId;
                ViewBag.backAddress = _backAddress;
                if (string.IsNullOrEmpty(member.SFTUserId))//没有盛付通账号
                {
                    ViewBag.temp = "没有开通盛付通";
                    //盛付通接口应改成 member.SFTUserName; QJ13818609394
                    ViewBag.userName = member.SFTUserName; //"quanju_" + member.Name;
                }
                else
                {
                    ViewBag.temp = "已开通盛付通";
                    ViewBag.userName = member.SFTUserName;
                }
                company = _companyService.GetCompany(member.ID);
                U_Member member1 = _memberService.getMemberInfo(member.ID);
                ViewBag.memberInfo = member1;
            }
            if (company != null)
            {
                if (company.Status == 2)
                {
                    ViewBag.CompanyName = company.CompanyName;
                    ViewBag.Faxes = company.Faxes;
                }
                ViewBag.Status = company.Status;
            }
            else
            {
                ViewBag.Status = 0;
            }
            return View();
        }
        #endregion

        #region 修改登陆密码
        //修改密码
        public ActionResult ChangePassword()
        {
            string a = RouteData.Values["controller"].ToString();
            string b = RouteData.Values["action"].ToString();
            string url = "/" + a + "/" + b;
            ViewBag.myUrl = url;
            return View();
        }

        //保存密码
        [HttpPost]
        public ActionResult ChangePassword(FormCollection collection)
        {
            JsonSMsg msg = new JsonSMsg();
            string newPassword = collection["newpwd"];
            string newPassword2 = collection["newpwd1"];
            if (MD5Util.GetMD5_32(collection["oldpwd"]) != ((U_Member)Session["CurrentUser"]).Password)
            {
                msg.Status = -1;
                msg.Message = "原密码错误";
                return Json(msg);
            }

            U_Member member = (U_Member)Session["CurrentUser"];
            member.Password = MD5Util.GetMD5_32(newPassword2);
            _memberService.SaveMember(member);

            msg.Status = 1;
            msg.Message = "修改成功";
            msg.Data = "/Account/Index";

            return Json(msg);
        }
        #endregion

        #region 支付密码

        //设置支付密码
        public ActionResult SetPayPwd()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SetPayPwd(FormCollection form)
        {
            JsonSMsg msg = new JsonSMsg();

            U_Member member = Session["CurrentUser"] as U_Member;

            U_Account account = new U_Account();

            account.MemberId = member.ID;
            account.AccountName = member.Name;
            account.PayPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(form["newpwd"], "md5");
            account.Status = member.Status;
            account.CreateTime = DateTime.Now;

            if (form["code"].ToString().Equals(Session["ValidateCode"].ToString()))
            {
                int result = _aservice.InsertAccount(account);

                if (result > 0)
                {
                    _memberService.PayValidate(member.ID);
                    msg.Status = 1;
                    msg.Message = "支付密码设置成功！";
                    msg.Data = Url.Action("Index");
                }
                else
                {
                    msg.Status = -1;
                    msg.Message = "支付密码设置失败！";
                }
            }
            else
            {
                msg.Status = -1;
                msg.Message = "验证码错误！";
            }

            return Json(msg);
        }


        //修改支付密码
        public ActionResult ChangePayPwd()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ChangePayPwd(FormCollection form)
        {
            JsonSMsg msg = new JsonSMsg();

            U_Member member = Session["CurrentUser"] as U_Member;
            string newPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(form["newpwd1"], "md5");

            int PayPwdIsValidate = _memberService.ValidatePayPass(member.Name, form["accName"], newPwd);

            int result = PayPwdIsValidate > 0 ? _memberService.UpdatePaypwd(member.ID, newPwd) : -1;

            if (result > 0)
            {
                msg.Status = 1;
                msg.Message = "支付密码修改成功！";
                msg.Data = Url.Action("Index");
            }
            else
            {
                if (result == -1)
                {
                    msg.Status = -2;
                    msg.Message = "账户不存在或支付密码错误！";
                }
                else
                {
                    msg.Status = -1;
                    msg.Message = "修改失败！";
                }
            }

            return Json(msg);
        }


        //找回支付密码
        public ActionResult FindPayPwd()
        {
            return View();
        }
        [HttpPost]
        public ActionResult FindPayPwd(FormCollection collection)
        {
            JsonSMsg msg = new JsonSMsg();


            return Json(msg);
        }

        #endregion

        #region 手机认证

        public ActionResult PhoneCertification()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SendValidateCode(string Mobilenumber)
        {
            JsonSMsg msg = new JsonSMsg();
            if (MD5Util.GetMD5_32(Request["txtPwd"]) != ((U_Member)Session["CurrentUser"]).Password)
            {
                msg.Status = -1;
                msg.Message = "请重新输入登陆密码";
                return Json(msg);
            }


            ISysTemplateService templateService = new SysTemplateService();
            var templateModel = templateService.GetSysTemplate("usercode");

            Session[RBSKeys.SESSION_SMS_CODE] = Utility.Number(6);
            string smstemp = templateModel.TemplateContent;
            smstemp = smstemp.Replace("{code}", Session[RBSKeys.SESSION_SMS_CODE].ToString());
            smstemp = smstemp.Replace("{valid}", "3");

            var m = "";
            if (SmsMessage.Send(Mobilenumber, smstemp, 1, out m))
            {
                msg.Status = 1;
                msg.Data = m;
            }
            else
            {
                msg.Status = -1;
            }
            return Json(msg, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult PhoneCertification(FormCollection form)
        {
            JsonSMsg msg = new JsonSMsg();
            if (MD5Util.GetMD5_32(Request["txtPwd"]) != ((U_Member)Session["CurrentUser"]).Password)
            {
                msg.Status = -1;
                msg.Message = "请重新输入登陆密码";
                return Json(msg);
            }
            U_Member member = new U_Member();
            member.ID = (Session["CurrentUser"] as U_Member).ID;
            member.Mobilenumber = form["Mobilenumber"];
            int result = _memberService.ValidatePhone(member);
            if (result > 0)
            {
                msg.Status = 1;
                msg.Message = "手机已成功认证！";
                msg.Data = Url.Action("Index");
            }
            else
            {
                msg.Status = -1;
                msg.Message = "认证失败！";
            }

            return Json(msg);
        }

        #endregion

        #region 邮箱认证
        public ActionResult EmailCertification()
        {
            var member = (U_Member)Session["CurrentUser"];
            ViewBag.Id = member.ID;
            return View();
        }
        public JsonResult SendCertification(FormCollection form)
        {
            JsonSMsg rMsg = new JsonSMsg();
            //获取登陆密码
            if (MD5Util.GetMD5_32(Request["txtPwd"]) != ((U_Member)Session["CurrentUser"]).Password)
            {
                rMsg.Status = -1;
                rMsg.Message = "验证失败，请重新填写登陆密码";
            }
            else
            {
                //获取验证码
                var validateCode = form["validateCode"];
                if (validateCode != Session["ValidateCode"].ToString())
                {
                    rMsg.Status = -1;
                    rMsg.Message = "验证码错误";
                }
                else
                {
                    var siteconfig =
                        (S_Siteconfig)
                        SerializationHelper.Load(typeof(S_Siteconfig), Utility.GetXmlMapPath("Configpath"));
                    var config = _siteconfigService.LoadConfig();

                    //获取邮件短信模板 模板名字(registerlink)
                    var templateModel = _templateService.GetSysTemplate("registerlink");
                    var mail = new MailMessage();


                    var recipient = new[] { form["Email"] };
                    mail.AddRecipients(recipient);
                    mail.From = siteconfig.Emailfrom;
                    mail.FromName = Server.HtmlEncode(siteconfig.Emailnickname);
                    mail.BodyFormat = MailFormat.HTML;

                    //加密
                    string md5id = Base64Util.Encrypt(form["ID"]);
                    string md5email = Base64Util.Encrypt(form["Email"]);

                    //标题
                    mail.Subject = templateModel.TemplateName;
                    //内容
                    string mailContent = templateModel.TemplateContent;
                    mailContent = mailContent.Replace("{webname}", siteconfig.Webname);
                    mailContent = mailContent.Replace("{weburl}", siteconfig.Weburl);
                    mailContent = mailContent.Replace("{webtel}", siteconfig.Webtel);
                    mailContent = mailContent.Replace("{username}", "用户名");
                    mailContent = mailContent.Replace("{linkurl}",
                                                      config.Weburl + "/Login/checkEmail?MemberId=" + md5id + "&Email=" +
                                                      md5email);
                    // mailContent = mailContent.Replace("{linkurl}", config.Weburl + "/Login/checkEmail?MemberId=" + form["ID"] + "&Email=" + form["Email"]);
                    mailContent = mailContent.Replace("{valid}", "1");

                    mail.Body = mailContent;
                    mail.Charset = "gb2312";
                    var sp = new SmtpClient { SmtpServer = siteconfig.Emailsmtp };

                    sp.Send(mail, siteconfig.Emailusername, siteconfig.Emailpassword);
                    rMsg.Status = 1;
                    rMsg.Message = "发送成功,请到邮箱进行验证！";
                    //修改会员状态
                    U_Member member = _memberService.getMemberInfo(Convert.ToInt32(form["ID"]));
                    member.IsEmailValidate = false;
                    member.Email = "";
                    var ret = _memberService.SaveMember(member);
                    //清空session
                    Session["CurrentUser"] = member;



                    rMsg.Data = Url.Action("Index", "Account");
                }
            }
            return Json(rMsg);
        }

        #endregion

        #region 实名认证
        public ActionResult PersonalCertification()
        {
            var member = (U_Member)Session["CurrentUser"] as LY.Entity.U_Member;
            ViewBag.SftAddress = _sftAddress;
            ViewBag.merchantNo = _merchantNo;
            ViewBag.SFTUserId = member.SFTUserId;
            ViewBag.backAddress = _backAddress;
            if (string.IsNullOrEmpty(member.SFTUserId))//没有盛付通账号
            {
                ViewBag.temp = "没有开通盛付通";
                //盛付通接口应改成 member.SFTUserName; QJ13818609394
                ViewBag.userName = member.SFTUserName; //"quanju_" + member.Name;
            }
            else
            {
                ViewBag.temp = "已开通盛付通";
                ViewBag.userName = member.SFTUserName;
            }
            return View(member);
        }
        [HttpPost]
        public ActionResult PersonalCertification(U_Member member)
        {
            var msg = new JsonSMsg();
            //var model = Session["CurrentUser"] as U_Member;
            //if (model != null)
            //{
            //    model.IDType = 1;
            //    model.IDCode = member.IDCode;
            //    model.RealName = member.RealName;
            //}
            //if (_memberService.SaveMember(model) > 0)
            //{
            //    msg.Status = 1;
            //    msg.Message = "实名认证资料已提交!";
            //    msg.Data = Url.Action("Index");
            //    Session["CurrentUser"] = member;//将修改后的值重新加载到session中。
            //}
            //else
            //{
            //    msg.Status = -1;
            //    msg.Message = "修改失败";
            //}
            return Json(msg);
        }
        #endregion

        #region 测试
        public ActionResult Test()
        {
            //var siteconfig = (S_Siteconfig)SerializationHelper.Load(typeof(S_Siteconfig), Utility.GetXmlMapPath("Configpath"));

            ////获取邮件短信模板 模板名字(registerlink)
            //var templateModel = _templateService.GetSysTemplate("registerlink");
            //var mail = new MailMessage();
            //// var ma = new MailAttachments();
            ////  ma.Add(@"附件地址");
            ////  mail.Attachments = ma;

            //var recipient = new[] { "admin@shcmjgs.com", "1179802910@qq.com" };
            //mail.AddRecipients(recipient);
            //mail.From = siteconfig.Emailfrom;
            //mail.FromName = Server.HtmlEncode(siteconfig.Emailnickname);
            //mail.BodyFormat = MailFormat.HTML;

            ////标题
            //mail.Subject = templateModel.TemplateName;
            ////内容
            //string mailContent = templateModel.TemplateContent;
            //mailContent = mailContent.Replace("{webname}", siteconfig.Webname);
            //mailContent = mailContent.Replace("{weburl}", siteconfig.Weburl);
            //mailContent = mailContent.Replace("{webtel}", siteconfig.Webtel);
            //mailContent = mailContent.Replace("{username}", "用户名");
            //mailContent = mailContent.Replace("{linkurl}", "http://www.baidu.com");
            //mailContent = mailContent.Replace("{valid}", "1");

            //mail.Body = mailContent;
            //mail.Charset = "gb2312";
            //var sp = new SmtpClient { SmtpServer = siteconfig.Emailsmtp };

            //sp.Send(mail, siteconfig.Emailusername, siteconfig.Emailpassword);


            ////发送短信 

            //var msg = "短信返回信息";
            ////if (SmsMessage.Send("18049905636", "您本次的验证码为:" + LY.Common.Utility.Number(6) + "【建周科技】", 1, out msg))
            ////{
            ////    return Content(msg);
            ////}


            //var userinfo = SmsMessage.GetAccountQuantity();


            //ViewData.Model = userinfo;

            string quertString = "" + "errorCode=" + "200" + "&errorMessage=" + "请求成功完成" + "&merchantNo=" + "529477" + "&sdpUserId="
                + "v.pt.12170818.p2p" + "&timestamp=" + "20151231144722" + "&userName=" + "quanju_sunmin2";
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, "Y+pF9iHUCPKMBekLCpXf+tCPhFlWI/N4A9XK9DihNTbqRWmzsyyy8VWG8KpfuYGmVsUgAs2V6ac/Yom44RdDxpS4AiT2glJ7bTI/wKGwwPh4Mj18pbM0eA4c1rHV07M3NhHnFiQliC0TwdtyEIAMrCU3dbcf6fYyqN5DSCO+2dc=");
            return null;


            return View();
        }
        #endregion

        #region 个人设置
        public ActionResult PersonSet()
        {
            var member = (U_Member)Session["CurrentUser"];
            return View(member);
        }

        [HttpPost]
        public JsonResult PersonSet(U_Member member)
        {
            JsonSMsg msg = new JsonSMsg();
            var model = Session["CurrentUser"] as U_Member;
            if (model != null)
            {
                model.Sex = member.Sex;
                model.Birthday = member.Birthday;
                model.Address = member.Address;
                model.Nickname = member.Nickname;
                model.HeadImage = member.HeadImage;
            }
            if (_memberService.SaveMember(model) > 0)
            {
                msg.Status = 1;
                msg.Message = "个人资料更新成功";
                //msg.Data = Url.Action("Index");
                Session["CurrentUser"] = model;//将修改后的值重新加载到session中。
            }
            else
            {
                msg.Status = -1;
                msg.Message = "个人资料更新失败";
            }

            return Json(msg);
        }

        #endregion

        #region 收货地址

        public ActionResult UserAddress(int? ProjectId, int? ProjectItemId, int Id = 0)
        {
            //存储点击订单支持时的项目ID和回报id 还有订单编号
            if (ProjectId != null && ProjectItemId != null)
            {
                Session["ProjectId"] = ProjectId;
                Session["ProjectItemId"] = ProjectItemId;
            }
            Session["proOrderId"] = Id;

            U_Member member = (U_Member)Session["CurrentUser"];
            //ViewData.Model = _memberService.GetAllUserAddress(member.ID);
            ViewBag.Mid = member.ID;
            return View();
        }

        [HttpPost]
        public ActionResult UserAddressList(UserAddressSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];

            PagedList<U_UserAddress> bList = _memberService.GetUserAddressList(search, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<U_UserAddress>(bList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        //新增收货地址
        public ActionResult UserAddressEdit(int Id = 0)
        {
            U_UserAddress userAddress = null;
            if (Id > 0)
            {
                //编辑
                userAddress = _memberService.GetAddress(Id);
            }
            else
            {
                //新增
                U_Member member = (U_Member)Session["CurrentUser"];
                userAddress = new U_UserAddress() { MemberId = member.ID, Addtime = DateTime.Now };

                //ViewData.Model = model;
            }

            return View(userAddress);
        }

        [HttpPost]
        public JsonResult SaveAddressEdit(U_UserAddress collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                int r = 0;
                if (collection.IsDefault == 1)
                {
                    //先删除其他的默认地址
                    r = _memberService.UpdateDefaultAddress(collection.MemberId);
                }
                int ret = _memberService.SaveUserAddress(collection);

                if (ret > 0)
                {
                    //判断是否是添加回报时设置
                    if (Session["ProjectItemId"] != null && Session["ProjectId"] != null)
                    {
                        rMsg.Status = 2;
                        rMsg.Data = "/UserOrder/AddOrder?itemid=" + Convert.ToInt32(Session["ProjectItemId"]) + "&ProjectId=" + Convert.ToInt32(Session["ProjectId"]) + "&Id=" + Convert.ToInt32(Session["proOrderId"]);

                    }
                    else
                    {
                        rMsg.Status = 1;
                        rMsg.Data = Url.Action("UserAddress");
                        rMsg.Message = "操作成功！";
                    }
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }
        //设置或取消默认地址
        [HttpPost]
        public JsonResult SetDefault(int id, int memberid)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                //string errmsg = "";
                //先删除其他的默认地址
                int r = _memberService.UpdateDefaultAddress(memberid);
                int ret = _memberService.SetDefaultAddress(id);
                if (ret > 0)
                {
                    //判断是否是添加回报时设置
                    if (Session["ProjectItemId"] != null && Session["ProjectId"] != null)
                    {
                        rMsg.Status = 2;
                        rMsg.Data = "/UserOrder/AddOrder?itemid=" + Convert.ToInt32(Session["ProjectItemId"]) + "&ProjectId=" + Convert.ToInt32(Session["ProjectId"]) + "&Id=" + Convert.ToInt32(Session["proOrderId"]);

                    }
                    else
                    {
                        rMsg.Status = 1;
                        rMsg.Message = "操作成功！";
                    }

                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //删除收货地址
        //删除链接
        [HttpPost]
        public JsonResult AddrDelete(int id)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                }

                int ret = _memberService.DeleteUserAddress(id);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {

                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }


        #endregion

        #region 银行卡
        //银行卡绑定信息界面
        public ActionResult BankCardList()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            ViewBag.Mid = member.ID;

            //http://wdtest.shengpay.com/user/card/manage.html

            //     http://wdtest.shengpay.com/user/card/manage.html

            return View(member);
        }
        [HttpPost]
        public ActionResult BankcardList(BankCardSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<U_BankCard> bList = _bank.Getbank(search.MemberID, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<U_BankCard>(bList, colkey, colsinfo.Split(','));
            return Json(at);
        }
        //绑定银行卡界面
        public ActionResult BankCardAdd(int id = 0)
        {
            U_BankCard card = null;
            if (id > 0)
            {
                //编辑
                card = _bank.GetcardByID(id);
                ViewBag.sign = 1;
            }
            else
            {
                //新增
                U_Member member = (U_Member)Session["CurrentUser"];
                card = new U_BankCard();
                card.MemberId = member.ID;
                card.AddTime = DateTime.Now;
                ViewBag.sign = 2;
            }
            return View(card);
        }

        [HttpPost]
        public ActionResult SaveBankCard(U_BankCard card)
        {
            JsonSMsg msg = new JsonSMsg();
            card.AddTime = DateTime.Now;

            if (_bank.BindCard(card) > 0)
            {
                msg.Status = 1;
                msg.Data = Url.Action("BankcardList");
                msg.Message = "银行卡绑定成功！";
            }
            else
            {
                msg.Status = -1;
                msg.Message = "银行卡绑定失败！";
            }
            return Json(msg);
        }

        //取消绑定
        //删除链接
        [HttpPost]
        public JsonResult BankCardDelete(int id)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                }

                int ret = _bank.deleteCard(id);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {

                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }
        #endregion

        #region 公司信息
        public ActionResult CompanyApprove()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            U_Company company = _companyService.GetCompany(member.ID);
            List<U_Companydocument> companydocumentlist = null;
            if (company != null)
            {
                companydocumentlist = _companydocument.GetCompanydocumentList(company.Id);//获取图片
            }
            ViewBag.Companydocument = companydocumentlist;

            ViewBag.Company = company;
            return View();
        }

        [HttpPost]
        public ActionResult SaveCompanyInfo(U_Company company, FormCollection collection)
        {
            JsonSMsg msg = new JsonSMsg();
            U_Member member = (U_Member)Session["CurrentUser"];
            //修改用户状态为个人用户
            member.Classify = "个人";
            int ret2 = _memberService.SaveMember(member);
            //清空session
            Session["CurrentUser"] = member;
            company.MemberId = member.ID;
            string action = Request["btnSave"];
            if (action == "提交")
            {
                company.Status = (int)LY.Common.Enum.CompanyStatus.审核中;
            }
            else
            {
                company.Status = (int)LY.Common.Enum.CompanyStatus.未认证;
            }
            int ret = _companyService.SaveCopmpany(company);//保存公司基本信息

            U_Companydocument img = new U_Companydocument();
            if (company.Id == 0)
            {
                img.CompanyId = ret;
            }
            else
            {
                img.CompanyId = company.Id;
            }
            if (ret > 0)
            {
                //添加公司附件信息
                img.DocPath = collection["hid_pic"];
                AddImages(img);
                if (action == "提交")
                {
                    msg.Status = 1;
                    msg.Message = "提交成功，请耐心等待审核结果";
                }
                else
                {
                    msg.Status = 1;
                    msg.Message = "公司信息保存成功！";
                }
            }
            else
            {
                msg.Status = -1;
                msg.Message = "操作失败！";
            }

            return Json(msg);
        }

        #region 上传图片到本地
        public static List<ReturnParameters> rlist = new List<ReturnParameters>();
        [HttpPost]
        public ActionResult UpLoadProcess(UploadParameters para)
        {
            ReturnParameters path = new ReturnParameters();
            ActionResult json = new UploadImages("Upload", new string[]{ 
                "Upload/FuJian"
            }).UpLoadProcess(para, ref path);

            rlist.Add(path);
            return json;

        }

        //添加图片
        private int AddImages(U_Companydocument img)
        {
            List<U_Companydocument> imgList = new List<U_Companydocument>();
            int result = 0;
            if (rlist.Count > 0)
            {
                //string[] arr = img.DocPath.Remove(img.DocPath.LastIndexOf(',')).Split(',');
                foreach (var item in rlist)//遍历容器
                {
                    U_Companydocument newimg = new U_Companydocument();

                    newimg.DocPath = item.filePath;

                    newimg.CompanyId = img.CompanyId;

                    imgList.Add(newimg);
                }
                result = _companydocument.AddImages(imgList);
            }
            return result;
        }

        public JsonResult DeleteImages(string id, int? sign = null)
        {
            JsonSMsg msg = new JsonSMsg();
            int result = _companydocument.DeleteImages(int.Parse(id));
            //修改状态为”未认证“
            if (sign != null && Session["CurrentUser"] != null)
            {
                U_Member member = (U_Member)Session["CurrentUser"];
                U_Company company = _companyService.GetCompany(member.ID);
                company.Status = (int)LY.Common.Enum.CompanyStatus.未认证;
                int ret = _companyService.SaveCopmpany(company);//保存公司基本信息
                member.Classify = "个人";
                int ret2 = _memberService.SaveMember(member);
                Session["CurrentUser"] = member;
            }
            if (result > 0)
            {
                msg.Status = 1;
                msg.Message = "操作成功！";
            }
            else
            {
                msg.Status = -1;
                msg.Message = "操作失败！";
            }

            return Json(msg);

        }

        #endregion


















        #endregion

        #region 生成签名
        //冲值是签名的生成方法，因为它的排序规则和别的不同
        public ActionResult GetSign()
        {
            MySign mysign = new MySign();
            string strOrigin = Request["sign"];
            strOrigin = strOrigin.Replace("|", "&");
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            strOrigin = strOrigin.Replace("temp", time);
            strOrigin = strOrigin.Replace("orderNum", time.Substring(2, 12));//在后台生成订单那号
            return Content(time + mysign.GetSign(strOrigin));
        }

        /// <summary>
        /// 生成签名的方法 用sort()方法排序，这里于java有区别 这里的小写排在前面 而java是大写字母排前面
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSign2()
        {
            MySign mysign = new MySign();
            string strOrigin = Request["sign"];
            Array array = strOrigin.Split('|');
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            Array.Sort(array);
            //string tmp = string.Join("&", array);
            string tmp = "";
            for (int i = 0; i < array.Length; i++)
            {
                if (((string[])(array))[i].Contains("timestamp"))//替换时间
                {
                    ((string[])(array))[i] = ((string[])(array))[i].Replace("temp", time);
                }
                if (((string[])(array))[i].Contains("withdrawNo"))//替换提现的编号
                {
                    string order = time.Substring(2, 12);
                    ((string[])(array))[i] = ((string[])(array))[i].Replace("orderNum", order);
                }
                if (((string[])(array))[i].Contains("submitBidNo"))//替换投标的编号
                {
                    string order = time.Substring(2, 12);
                    ((string[])(array))[i] = ((string[])(array))[i].Replace("orderNum", order);
                }
                tmp += ((string[])(array))[i] + "&";
            }
            tmp = tmp.Substring(0, tmp.Length - 1);
            return Content(time + mysign.GetSign(tmp));
        }

        public string GetSign3(string[] array)
        {
            MySign mysign = new MySign();
            Array myarray = array;
            Array.Sort(myarray);
            string temp = "";
            for (int i = 0; i < array.Length; i++)
            {
                temp += array[i] + "&";
            }
            temp = temp.Substring(0, temp.Length - 1);
            return mysign.GetSign(temp);
        }
        #endregion

        #region 盛付通账号信息
        public ActionResult AccountInfo()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            ViewBag.SftAddress = _sftAddress;
            ViewBag.merchantNo = _merchantNo;
            ViewBag.SFTUserId = member.SFTUserId;
            ViewBag.backAddress = _backAddress;
            if (string.IsNullOrEmpty(member.SFTUserId))//没有盛付通账号
            {
                ViewBag.temp = "没有开通盛付通";
                ViewBag.userName = "QJ" + member.Mobilenumber; //这里定义的规则是QJ+手机号
            }
            else
            {
                ViewBag.temp = "已开通盛付通";
                ViewBag.userName = member.SFTUserName;
                string strJson = SelectSftUserBalance();
                List<decimal> list = _aservice.QueryAccountInfo(member.ID);
                JavaScriptSerializer js = new JavaScriptSerializer();
                Dictionary<string, string> dic = new Dictionary<string, string>();
                Type type = typeof(Dictionary<string, string>);
                dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
                if (dic["errorMessage"] == "平台用户未开户")
                {
                    ViewBag.totalAmount = 0;
                    ViewBag.availableAmount = 0;
                    ViewBag.frozenAmount = 0;
                }
                else
                {
                    ViewBag.totalAmount = list[0];
                    ViewBag.availableAmount = list[1];
                    ViewBag.frozenAmount = dic["frozenAmount"];
                }
                //FundsFlow_EX funds = _fservice.GetAccountInfo(member.ID);
                //if (funds == null)
                //{
                //    ViewBag.ValidAmt = 0;
                //}
                //else
                //{
                //    ViewBag.AvailableAmt = funds.AvailableAmt;
                //    //账户资金
                //}
                //ViewBag.Funds = funds;
                ViewBag.leijichongzhi = list[2];
                ViewBag.leijitouzi = list[3];
                ViewBag.leijishouyi = list[4];
            }
            return View(member);
        }

        //开通盛付通的中间页面
        public ActionResult AccountInfoMiddlePage(string realName, string idCardNo)
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            string[] array = new string[6];
            array[0] = "merchantNo=" + _merchantNo;
            array[1] = "timestamp=" + time;
            array[2] = "userName=" + "QJ" + member.Mobilenumber; //这里定义的规则是QJ+手机号;
            array[3] = "realName=" + Server.HtmlDecode(realName);
            array[4] = "idCardNo=" + idCardNo;
            array[5] = "callback=" + _backAddress + "/Account/RegisterCallBack";
            //array[5] = "callback=" + "/Account/RegisterCallBack";

            ViewBag.SftAddress = _sftAddress;
            ViewBag.merchantNo = _merchantNo;
            ViewBag.timestamp = time;
            ViewBag.userName = "QJ" + member.Mobilenumber;
            ViewBag.realName = Server.HtmlDecode(realName);
            ViewBag.idCardNo = idCardNo;
            ViewBag.backAddress = _backAddress + "/Account/RegisterCallBack";
            ViewBag.sign = GetSign3(array);
            //更新会员表的数据，把实名和省份证号存到表中
            member.IDCode = idCardNo;
            member.RealName = realName;
            member.SFTUserName = "QJ" + member.Mobilenumber; //这里定义的规则是QJ+手机号;
            _memberService.SaveMember(member);
            return View();
        }

        //开通盛付通之前，先将姓名和省份证先输入，如果那边返回的结果是对的那么就完成了实名认证，如果是错误就清除
        public ActionResult SftRegister()
        {
            MySign mysign = new MySign();
            string strOrigin = Request["sign"];
            Array array = strOrigin.Split('|');
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            Array.Sort(array);
            string tmp = "";
            for (int i = 0; i < array.Length; i++)
            {
                if (((string[])(array))[i].Contains("timestamp"))//替换时间
                {
                    ((string[])(array))[i] = ((string[])(array))[i].Replace("temp", time);
                }
                tmp += ((string[])(array))[i] + "&";
            }
            //更新会员表的数据，把实名和省份证号存到表中
            U_Member member = (U_Member)Session["CurrentUser"];
            member.IDCode = Request["idCardNo"];
            member.RealName = Request["realName"];
            member.SFTUserName = Request["userName"];
            _memberService.SaveMember(member);
            tmp = tmp.Substring(0, tmp.Length - 1);
            return Content(time + mysign.GetSign(tmp));
        }

        //盛付通注册成功后返回的地址
        [MyAuthorization(IsLoginValidate = "false")]
        public ActionResult RegisterCallBack()
        {
            MyLog.Write(Request["errorCode"]);
            MyLog.Write(Request["errorMessage"]);
            MyLog.Write(Request["merchantNo"]);
            MyLog.Write(Request["timestamp"]);
            MyLog.Write(Request["userName"]);
            MyLog.Write(Request["sdpUserId"]);
            MyLog.Write(Request["sign"]);
            ViewBag.errorCode = Request["errorCode"];
            ViewBag.errorMessage = Request["errorMessage"];
            ViewBag.merchantNo = Request["merchantNo"];
            ViewBag.timestamp = Request["timestamp"];
            ViewBag.userName = Request["userName"];
            ViewBag.sdpUserId = Request["sdpUserId"];
            ViewBag.sign = Request["sign"];
            string quertString = "" + "errorCode=" + Request["errorCode"] + "&errorMessage=" + Request["errorMessage"] + "&merchantNo=" + Request["merchantNo"] + "&sdpUserId="
                + Request["sdpUserId"] + "&timestamp=" + Request["timestamp"] + "&userName=" + Request["userName"];
            MyLog.WriteLog("用户开户", quertString);

            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, Request["sign"]);
            if (result)
            {
                ViewBag.Result = "验证数据正确,开户成功";
                if (Request["errorMessage"] == "请求成功完成")
                {
                    U_Member member = _memberService.GetModelBySftUserName(Request["userName"]);
                    member.SFTUserId = Request["sdpUserId"];
                    member.IsIDValidate = true;
                    _memberService.SaveMember(member);
                    Session["CurrentUser"] = member;//这里是更新Session
                }
                else
                {
                    U_Member member = _memberService.GetModelBySftUserName(Request["userName"]);
                    member.SFTUserName = "";
                    member.RealName = "";
                    member.IDCode = "";
                    _memberService.SaveMember(member);
                }
            }
            else
            {
                ViewBag.Result = "验证数据失败,请稍后再尝试";
            }
            //return RedirectToAction("AccountInfo", "Account");
            return View();
        }

        //去盛付通页面查看信息的中间页面
        public ActionResult QuShengFuTongMiddlePage(string userName)
        {
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            string[] array = new string[3];
            array[0] = "merchantNo=" + _merchantNo;
            array[1] = "timestamp=" + time;
            array[2] = "userName=" + userName;
            ViewBag.SftAddress = _sftAddress;
            ViewBag.merchantNo = _merchantNo;
            ViewBag.timestamp = time;
            ViewBag.userName = userName;
            ViewBag.sign = GetSign3(array);
            return View();
        }
        #endregion

        #region 查询商户资金
        //查询商户账户余额（企业）
        public ActionResult SelectsftShangHu()
        {
            string merchantNo = _merchantNo;
            string relatedMerchantNo = _merchantNo;
            string sign = "merchantNo=" + merchantNo + "&relatedMerchantNo=" + relatedMerchantNo;
            MySign mysign = new MySign();
            string temp = mysign.GetSign(sign);
            string newsign = Server.UrlEncode(temp);
            // 初始化WebClient
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            // 要提交表单的URI字符串。
            string postString = "?sign=" + newsign;//merchantAccount/{merchantNo}-{relatedMerchantNo}
            string url = _apiAddress + "/merchantAccount/" + merchantNo + "-" + relatedMerchantNo + postString;
            // 将字符串转换成字节数组-
            byte[] postData = Encoding.ASCII.GetBytes(postString);
            // 上传数据，返回页面的字节数组
            byte[] responseData = webClient.DownloadData(url);
            // 返回的将字节数组转换成字符串(HTML)
            string strJson = Encoding.UTF8.GetString(responseData);

            //验证返回数据
            JavaScriptSerializer js = new JavaScriptSerializer();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Type type = typeof(Dictionary<string, string>);
            dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
            string[] queryString = new string[7];
            queryString[0] = "errorCode=" + dic["errorCode"];
            queryString[1] = "errorMessage=" + dic["errorMessage"];
            queryString[2] = "merchantNo=" + dic["merchantNo"];
            queryString[3] = "timestamp=" + dic["timestamp"];
            queryString[4] = "relatedMerchantNo=" + dic["relatedMerchantNo"];
            queryString[5] = "availableAmount=" + dic["availableAmount"];
            queryString[6] = "frozenAmount=" + dic["frozenAmount"];
            Array array = queryString;
            Array.Sort(array);
            queryString = (string[])array;
            string hehe = string.Join("&", queryString);
            bool result = mysign.ValidateSign(hehe, dic["sign"]);
            if (result)
            {
                return Content(strJson);
            }
            else
            {
                return Content("数据验证失败");
            }
        }
        #endregion

        #region 资金记录
        //资金记录
        public ActionResult FundsList()
        {
            //账户资金
            //U_Member member = (U_Member)Session["CurrentUser"];
            //if (string.IsNullOrEmpty(member.SFTUserId))
            //{

            //}
            //else
            //{
            //    string strJson = SelectSftUserBalance();
            //    JavaScriptSerializer js = new JavaScriptSerializer();
            //    Dictionary<string, string> dic = new Dictionary<string, string>();
            //    Type type = typeof(Dictionary<string, string>);
            //    dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
            //    if (dic["errorMessage"] == "平台用户未开户")
            //    {
            //        ViewBag.totalAmount = 0;
            //        ViewBag.availableAmount = 0;
            //        ViewBag.frozenAmount = 0;
            //    }
            //    else
            //    {
            //        ViewBag.totalAmount = dic["totalAmount"];
            //        ViewBag.availableAmount = dic["availableAmount"];
            //        ViewBag.frozenAmount = dic["frozenAmount"];
            //    }
            //    FundsFlow_EX funds = _fservice.GetAccountInfo(member.ID);
            //    if (funds == null)
            //    {
            //        ViewBag.ValidAmt = 0;
            //    }
            //    else
            //    {
            //        ViewBag.AvailableAmt = funds.AvailableAmt;
            //        //账户资金
            //    }
            //    return View(funds);
            //}
            return View();
        }

        //查询用户账户余额（个人）
        public string SelectSftUserBalance()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            string userName = member.SFTUserName;
            string merchantNo = _merchantNo;
            string sign = "merchantNo=" + merchantNo + "&userName=" + userName;
            MySign mysign = new MySign();
            string temp = mysign.GetSign(sign);
            string newsign = Server.UrlEncode(temp);
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string postString = "?sign=" + newsign;
            string url = _apiAddress + "/userAccount/" + merchantNo + "-" + userName + postString;
            byte[] postData = Encoding.ASCII.GetBytes(postString);
            byte[] responseData = webClient.DownloadData(url);
            string strJson = Encoding.UTF8.GetString(responseData);
            //验证返回数据
            JavaScriptSerializer js = new JavaScriptSerializer();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Type type = typeof(Dictionary<string, string>);
            dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
            List<string> test = new List<string>(dic.Keys);
            test.Remove("sign");
            string[] queryString = new string[test.Count];
            for (int i = 0; i < test.Count; i++)
            {
                queryString[i] = test[i] + "=" + dic[test[i]];
            }
            Array array = queryString;
            Array.Sort(array);
            queryString = (string[])array;
            string hehe = string.Join("&", queryString);
            bool result = mysign.ValidateSign(hehe, dic["sign"]);
            if (result)
            {
                return strJson;
            }
            else
            {
                return "数据验证失败";
            }
        }

        public JsonResult FundsFlowList(FundsFlowSearch search, FormCollection form)
        {
            U_Member member = Session["CurrentUser"] as U_Member;
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            search.MemberId = member.ID;
            PagedList<U_FundsFlow> waList = _fservice.QueryFundsFlowList2(search, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<U_FundsFlow>(waList, colkey, colsinfo.Split(','));
            return Json(at);
        }
        #endregion

        #region 快速充值
        public ActionResult Recharge()
        {
            U_Member mm = (U_Member)Session["CurrentUser"];
            string ip = "";
            if (Request.ServerVariables["HTTP_VIA"] != null)
            {
                ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                ip = Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            ViewBag.IP = ip;
            ViewBag.sftDepositId = mm.SFTUserId;
            return View();
        }

        //充值的中间页面
        public ActionResult RechargeMiddlePpage(string money, string ip)
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            string traceNo = "quanju" + DateTime.Now.ToString("yyMMddHHmmss") + new Random().Next(0, 99999).ToString("00000"); //日期加5位随机数
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            string sign = "B2CPayment|V4.1.1.1.1|UTF-8|" + traceNo + "|" + _merchantNo + "|" + traceNo + "|" + money + "|" + time + "|" + _backAddress
                + "/Account/RechargePageUrl|" + _backAddress + "/Pay/RechargeNotifyUrl|" + ip + "|" + member.SFTUserId + "|" + "0002|RSA|";
            ViewBag.rechargeAddress = _rechargeAddress;
            ViewBag.traceNo = traceNo;
            ViewBag.merchantNo = _merchantNo;
            ViewBag.orderAmount = money;
            ViewBag.orderTime = time;
            ViewBag.backAddress = _backAddress;
            ViewBag.buyerIp = ip;
            ViewBag.sftDepositId = member.SFTUserId;
            ViewBag.signMsg = new MySign().GetSign(sign);
            //在点击充值的时候先在U_FundsFlow 里先添加一条记录
            U_FundsFlow fundsflow = new U_FundsFlow();
            fundsflow.Type = 1;//1表示充值
            fundsflow.Status = 0;
            fundsflow.MemberId = member.ID;
            fundsflow.InCome = decimal.Parse(money);
            fundsflow.CreateTime = DateTime.Now;
            fundsflow.OrderNo = traceNo;
            int i = _fservice.FundsFlowSave(fundsflow, "0");
            return View();
        }

        //盛付通充值后的PageUrl同步返回地址
        [MyAuthorization(IsLoginValidate = "false")]
        public ActionResult RechargePageUrl()
        {
            MyLog.Write("充值同步返回开始");
            //MyLog.Write(Request["Name"]);
            //MyLog.Write(Request["Version"]);
            //MyLog.Write(Request["Charset"]);
            //MyLog.Write(Request["TraceNo"]);
            //MyLog.Write(Request["MsgSender"]);
            //MyLog.Write(Request["SendTime"]);
            //MyLog.Write(Request["InstCode"]);
            //MyLog.Write(Request["OrderNo"]);
            //MyLog.Write(Request["OrderAmount"]);
            //MyLog.Write(Request["TransNo"]);
            //MyLog.Write(Request["TransAmount"]);
            //MyLog.Write(Request["TransStatus"]);
            //MyLog.Write(Request["TransType"]);
            //MyLog.Write(Request["TransTime"]);
            //MyLog.Write(Request["MerchantNo"]);
            //MyLog.Write(Request["ErrorCode"]); //这3个不是一定返回
            //MyLog.Write(Request["ErrorMsg"]);//这3个不是一定返回
            //MyLog.Write(Request["Ext1"]);//这3个不是一定返回
            //MyLog.Write(Request["SignType"]);

            //验证签名
            string queryString = Request["Name"] + "|" + Request["Version"] + "|" + Request["Charset"] + "|" + Request["TraceNo"] + "|"
                + Request["MsgSender"] + "|" + Request["SendTime"] + "|" + Request["InstCode"] + "|" + Request["OrderNo"] + "|"
                + Request["OrderAmount"] + "|" + Request["TransNo"] + "|" + Request["TransAmount"] + "|" + Request["TransStatus"] + "|"
                + Request["TransType"] + "|" + Request["TransTime"] + "|" + Request["MerchantNo"] + "|" + Request["SignType"] + "|";

            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(queryString, Request["SignMsg"]);
            if (result)
            {
                //找到当前充值的记录，修改资金和状态
                try
                {
                    U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["OrderNo"]);
                    U_BankInfo bankInfo = _bankInfo.GetBankInfo(Request["InstCode"]);
                    fundsflow.BankId = bankInfo.Id;
                    fundsflow.BankName = bankInfo.BankName;
                    if (Request["TransStatus"] == "01") //表示付款陈宫
                    {
                        fundsflow.Status = 1;
                    }
                    else
                    {
                        fundsflow.Status = -1;
                    }
                    int i = _fservice.UpdateFundsFlow(fundsflow);
                }
                catch (Exception ex)
                {
                    MyLog.Write(Request["OrderNo"]);
                    ViewBag.Result = ex.ToString();
                }
                ViewBag.Result = "充值成功";
            }
            else
            {
                ViewBag.Result = "充值失败,同步返回签名验证失败";
            }
            return View();
        }

        //查询出充值记录
        [HttpPost]
        public JsonResult RechargeList(FundsFlowSearch search, FormCollection form)
        {
            U_Member member = Session["CurrentUser"] as U_Member;
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            search.MemberId = member.ID;
            search.Type = 1;
            PagedList<U_FundsFlow> waList = _fservice.QueryFundsFlowList2(search, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<U_FundsFlow>(waList, colkey, colsinfo.Split(','));
            return Json(at);
        }
        #endregion

        #region 快速提现
        //快速提现
        public ActionResult Withdrawal()
        {
            //账户资金
            U_Member mm = (U_Member)Session["CurrentUser"];
            //账户资金
            //FundsFlow_EX funds = _fservice.GetAccountInfo(mm.ID);
            ViewBag.balance = _fservice.QueryBalance(mm.ID);
            ViewBag.SFTUserId = mm.SFTUserId;
            return View();
        }

        public ActionResult WithdrawMiddlePage(string money)
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            string withdrawNo = "quanju" + DateTime.Now.ToString("yyMMddHHmmss") + new Random().Next(0, 99999).ToString("00000"); //日期加5位随机数
            string[] array = new string[7];
            array[0] = "merchantNo=" + _merchantNo;
            array[1] = "timestamp=" + time;
            array[2] = "userName=" + member.SFTUserName;
            array[3] = "withdrawNo=" + withdrawNo;
            array[4] = "amount=" + money;
            array[5] = "callback=" + _backAddress + "/Account/WithdrawCallback";
            array[6] = "notifyUrl=" + _backAddress + "/Pay/WithdrawNotifyUrl";
            ViewBag.sftAddress = _sftAddress;
            ViewBag.merchantNo = _merchantNo;
            ViewBag.timestamp = time;
            ViewBag.SFTUserName = member.SFTUserName;
            ViewBag.withdrawNo = withdrawNo;
            ViewBag.amount = money;
            ViewBag.backAddress = _backAddress;
            ViewBag.sign = GetSign3(array);
            //在点击提现的时候先在U_FundsFlow 里先添加一条记录
            U_FundsFlow fundsflow = new U_FundsFlow();
            fundsflow.Type = 2;//表示提现
            fundsflow.Status = 0;
            fundsflow.MemberId = member.ID;
            fundsflow.OutPay = decimal.Parse(money) - 2;
            fundsflow.CreateTime = DateTime.Now;
            fundsflow.OrderNo = withdrawNo;
            int i = _fservice.FundsFlowSave(fundsflow, "2");
            return View();
        }

        //盛付通提现的同步返回
        [MyAuthorization(IsLoginValidate = "false")]
        public ActionResult WithdrawCallback()
        {
            MyLog.Write("提现同步返回开始");
            //MyLog.Write(Request["errorCode"]);
            //MyLog.Write(Request["errorMessage"]);
            //MyLog.Write(Request["timestamp"]);
            //MyLog.Write(Request["withdrawNo"]);
            //MyLog.Write(Request["amount"]);
            //MyLog.Write(Request["fee"]);
            //MyLog.Write(Request["result"]);
            //MyLog.Write(Request["sign"]);
            ViewBag.errorCode = Request["errorCode"];
            ViewBag.errorMessage = Request["errorMessage"];
            ViewBag.timestamp = Request["timestamp"];
            ViewBag.withdrawNo = Request["withdrawNo"];
            ViewBag.amount = Request["amount"];
            ViewBag.fee = Request["fee"];
            ViewBag.result = Request["result"];
            ViewBag.sign = Request["sign"];
            //验证签名
            string quertString = "" + "amount=" + Request["amount"] + "&errorCode=" + Request["errorCode"] + "&errorMessage=" + Request["errorMessage"] +
                "&fee=" + Request["fee"] + "&result=" + Request["result"] + "&timestamp=" + Request["timestamp"] + "&withdrawNo=" +
                Request["withdrawNo"];
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, Request["sign"]);
            if (result)
            {
                ViewBag.hehe = "验证数据正确";
                try
                {
                    if (Request["result"] == "1" || Request["result"] == "3")
                    {
                        U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["withdrawNo"], 2); //获取提现的那条记录
                        fundsflow.Status = 1; //这里没有写审核时间。。
                        //fundsflow.OutPay = Convert.ToDecimal(Request["amount"]) - Convert.ToDecimal(Request["fee"]);
                        int i = _fservice.UpdateFundsFlow(fundsflow);

                        U_FundsFlow fundsflow2 = _fservice.GetFundsFlowByOrderNo(Request["withdrawNo"], 6); //获取提现的手续费
                        fundsflow2.Status = 1;

                        int j = _fservice.UpdateFundsFlow(fundsflow2);
                        ViewBag.hehe = "验证数据正确,提现成功";
                    }
                    else
                    {
                        ViewBag.hehe = ViewBag.hehe + Request["result"];
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.hehe = ex.ToString();
                }
            }
            else
            {
                ViewBag.hehe = "验证数据失败";
            }
            return View();
        }

        //查询提现的记录
        public ActionResult WithdrawList(FundsFlowSearch search, FormCollection form)
        {
            U_Member member = Session["CurrentUser"] as U_Member;
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            search.MemberId = member.ID;
            search.Type = 2;
            PagedList<U_FundsFlow> waList = _fservice.QueryFundsFlowList2(search, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<U_FundsFlow>(waList, colkey, colsinfo.Split(','));
            return Json(at);
        }
        #endregion

    }
}
